#include "login.h"
#include "ui_login.h"

Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    // 方便调试, 记得删除~
    ui->nameEdit->setText("admin");
    ui->passwordEdit->setText("88888888");
    ui->nameEdit->setText("theodore");
    ui->passwordEdit->setText("a12345678");

    connect(ui->signBtn, &QPushButton::clicked, [=](){
        if (handleSignIn(u))
            QMessageBox::information(this, "提示", "注册成功");
    });
    connect(ui->loginBtn, &QPushButton::clicked, [=](){
        if (handleLogin(u)) {
            if (type == User::CONSUMER) {
                ConsumerSYS *cs = new ConsumerSYS(this->arg);
                cs->show();
               }
            else if (type == User::ADMIN) {
                AdminSYS *as = new AdminSYS(this->arg);
                as->show();
            }
            else {
                CourierSYS *cus = new CourierSYS(this->arg);
                cus->show();
            }
            this->close();
        }
        else {
            QMessageBox::warning(this, "登陆失败", "用户名或密码错误");
        }
    });

}

Login::~Login()
{
    delete ui;

}

void Login::getType()
{
    if (ui->userRBtn->isChecked())  type = User::CONSUMER;
    if (ui->workerRBtn->isChecked())    type = User::COURIER;
    if (ui->adminRBtn->isChecked())     type = User::ADMIN;
}

bool Login::handleSignIn(User *curUser)
{
    this->getType();
    QString username = ui->nameEdit->text();
    QString password = ui->passwordEdit->text();
    QString fileMsg;

    switch (type) {
        case User::CONSUMER:
            curUser = new Consumer();
            curUser->setInitInfo(username, password);
            fileMsg = username + "\t" + password + "\t用户";
            this->writeTOFile(fileMsg);
            return(curUser->signIn());
            break;
        default:
            break;
    }
    return false;
}

bool Login::handleLogin(User *curUser)
{
    this->getType();
    QString username = ui->nameEdit->text();
    QString password = ui->passwordEdit->text();
    QString ret;

    switch (type) {
        case User::CONSUMER:
            curUser = new Consumer();
            break;
        case User::ADMIN:
            curUser = new Admin();
            break;
        case User::COURIER:
            curUser = new Courier();
            break;
        default:
            break;
    }
    curUser->setInitInfo(username, password);
    ret = curUser->logIn();
    if (ret == username) {
        arg = ret;  // 把用户名传给具体系统
        return true;
    }
    else
        return false;
}

void Login::writeTOFile(QString msg)
{

    std::ofstream fp;
    fp.open("loginfo.txt", std::ios::app);
    fp << msg.toStdString() << std::endl;
}
